import { createSlice,createAsyncThunk } from '@reduxjs/toolkit'
import apiSlice from "@/store/request/apiSlice"

// 一个用于异步操作的 thunk 函数
export const incrementAsync = createAsyncThunk(
  'counter/incrementAsync',  
  async (params, thunkAPI) => {
    // console.log(thunkAPI.getState());
    const response = await fetch("/api/API/yyjhss.php?id=2140038547&type=wy")
    const data=await response.json()
    console.log(params,'params');
    // const { data } = await thunkAPI.dispatch(apiSlice.endpoints.CounterGetCounter.initiate());
    return data;
  }
)
export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0
  },
  reducers: {
    increment: state => {
      // Redux Toolkit 允许我们在 reducers 写 "可变" 逻辑。它
      // 并不是真正的改变状态值，因为它使用了 Immer 库
      // 可以检测到“草稿状态“ 的变化并且基于这些变化生产全新的
      // 不可变的状态
      state.value += 1
    },
    decrement: state => {
      state.value -= 1
    },
    incrementByAmount: (state, action) => {
      console.log(action);
      state.value = action.payload.value
    }
  },
  // 可以在 `extraReducers` 内对不同的 action 进行处理
  extraReducers:  builder => {
    builder.addCase(incrementAsync.fulfilled, (state, action) => {
      console.log("fulfilled",action);
      state.value = action.payload.code
    }).addCase(incrementAsync.pending, (state, action) => {
      console.log("pending");
    }).addCase(incrementAsync.rejected, (state, action) => {
      console.log("rejected");
    })
  }
})


export default counterSlice.reducer